<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="700px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="上级部门" prop="parent_id">
        <el-tree-select
          v-model="form.parent_id"
          :data="departmentTree"
          :props="{ label: 'name', value: 'id', children: 'children' }"
          placeholder="请选择上级部门"
          check-strictly
          clearable
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入部门编码" />
      </el-form-item>
      <el-form-item label="负责人" prop="leader">
        <el-input v-model="form.leader" placeholder="请输入负责人" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" :min="0" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  departmentId: {
    type: Number,
    default: null,
  },
})

const emit = defineEmits(['update:modelValue', 'success'])

const dialogVisible = ref(false)
const dialogTitle = ref('新增部门')
const loading = ref(false)
const formRef = ref(null)

const form = reactive({
  parent_id: 0,
  name: '',
  code: '',
  leader: '',
  phone: '',
  email: '',
  sort: 0,
  status: 1,
  remark: '',
})

const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入部门编码', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' },
  ],
}

const departmentTree = ref([])

// 监听对话框显示
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    if (props.departmentId) {
      dialogTitle.value = '编辑部门'
      loadDepartmentData()
    } else {
      dialogTitle.value = '新增部门'
      resetForm()
    }
    loadDepartmentTree()
  }
})

// 监听对话框关闭
watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 加载部门数据
const loadDepartmentData = async () => {
  try {
    const res = await request.get(`/departments/${props.departmentId}`)
    if (res.code === 200) {
      Object.assign(form, {
        parent_id: res.data.parent_id || 0,
        name: res.data.name,
        code: res.data.code,
        leader: res.data.leader || '',
        phone: res.data.phone || '',
        email: res.data.email || '',
        sort: res.data.sort || 0,
        status: res.data.status,
        remark: res.data.remark || '',
      })
    }
  } catch (error) {
    ElMessage.error('加载部门数据失败')
  }
}

// 加载部门树
const loadDepartmentTree = async () => {
  try {
    const res = await request.get('/departments', { params: { tree: true, status: 1 } })
    if (res.code === 200) {
      // 添加根节点
      departmentTree.value = [
        { id: 0, name: '根部门', children: res.data },
      ]
      // 如果是编辑，排除当前部门及其子部门
      if (props.departmentId) {
        departmentTree.value = filterDepartmentTree(departmentTree.value, props.departmentId)
      }
    }
  } catch (error) {
    console.error('加载部门树失败:', error)
  }
}

// 过滤部门树（排除指定部门及其子部门）
const filterDepartmentTree = (tree, excludeId) => {
  return tree.filter(node => {
    if (node.id === excludeId) {
      return false
    }
    if (node.children && node.children.length > 0) {
      node.children = filterDepartmentTree(node.children, excludeId)
    }
    return true
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    parent_id: 0,
    name: '',
    code: '',
    leader: '',
    phone: '',
    email: '',
    sort: 0,
    status: 1,
    remark: '',
  })
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  resetForm()
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const url = props.departmentId ? `/departments/${props.departmentId}` : '/departments'
        const method = props.departmentId ? 'put' : 'post'
        const response = await request[method](url, form)
        if (response.code === 200) {
          ElMessage.success(props.departmentId ? '更新成功' : '创建成功')
          dialogVisible.value = false
          emit('success')
        }
      } catch (error) {
        // 处理验证错误（422）
        // 从 error.errors 或 error.response.data.errors 获取错误信息
        const errors = error.errors || error.response?.data?.errors
        const status = error.response?.status
        const isValidationError = status === 422 && errors && Object.keys(errors).length > 0
        
        if (isValidationError) {
          // 获取第一个错误消息
          const firstErrorKey = Object.keys(errors)[0]
          const firstErrorMessage = Array.isArray(errors[firstErrorKey]) 
            ? errors[firstErrorKey][0] 
            : errors[firstErrorKey]
          
          // 显示第一个错误消息（确保用户能看到提示）
          if (firstErrorMessage) {
            ElMessage.error(firstErrorMessage)
          }
          
          // 尝试将错误设置到表单字段上（如果成功，字段下方会显示错误）
          if (formRef.value) {
            try {
              await nextTick()
              const fieldsToSet = {}
              Object.keys(errors).forEach((field) => {
                const fieldError = Array.isArray(errors[field]) ? errors[field][0] : errors[field]
                fieldsToSet[field] = {
                  message: fieldError,
                  validating: false
                }
              })
              
              if (typeof formRef.value.setFields === 'function' && Object.keys(fieldsToSet).length > 0) {
                formRef.value.setFields(fieldsToSet)
              }
            } catch (setFieldsError) {
              // 如果设置字段错误失败，错误消息已经显示，不需要额外处理
              console.error('设置字段错误失败:', setFieldsError)
            }
          }
        } else {
          // 其他错误显示错误消息
          const errorMessage = error.response?.data?.message || error.message || '操作失败'
          ElMessage.error(errorMessage)
        }
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped lang="scss">
</style>

